<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>功能测试页面</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; }
        .container { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        h3 { margin-top: 0; color: #333; }
        input[type="text"] { padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 10px; }
        button { padding: 8px 15px; color: white; border: none; border-radius: 4px; cursor: pointer; }
        .feign-test-button { background: #5cb85c; }
        .feign-test-button:hover { opacity: 0.8; }
        .test-result-area { margin-top: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; background: #f9f9f9; min-height: 50px; word-wrap: break-word; }
        .back-link { display: inline-block; margin-top: 20px; padding: 10px 15px; background-color: #4a89dc; color: white; text-decoration: none; border-radius: 5px; }
        .back-link:hover { background-color: #3b7dd8; }
    </style>
</head>
<body>
    <div class="container">
        <h3>OpenFeign 测试 (通过ID查询商品)</h3>
        <div style="margin-top: 10px;">
            <input type="text" id="feignTestItemId" placeholder="输入商品 ID">
            <button id="feignTestButton" class="feign-test-button">执行测试</button>
        </div>
        <div id="feignTestResult">
            测试结果将显示在这里...
        </div>
        <hr style="margin-top: 30px; margin-bottom: 20px;">

        <h3>熔断与降级测试 (针对 cloud-second-hand 应用的 ItemFeignClient)</h3>
        <p style="font-size: 0.9em; color: #555;">本测试将验证 <code>cloud-second-hand</code> 应用中对 <code>item-service</code> 调用的熔断与降级逻辑。您可以通过输入特定商品ID来模拟不同场景。</p>

        <h4>场景1: 正常调用 (ItemFeignClient &rarr; item-service)</h4>
        <p style="font-size: 0.9em; color: #555;">确保下游 <code>item-service</code> (如: localhost:8083) 正常运行。输入一个<strong>存在的商品ID</strong> (例如: 1, 2, ...)。</p>
        <div style="margin-top: 10px;">
            <input type="text" id="cbTestItemId1" placeholder="输入存在的商品ID">
            <button id="cbTestButtonStable" class="feign-test-button" style="background-color: #5cb85c;">1. 测试正常调用</button>
        </div>
        <div id="cbTestResult1" class="test-result-area">场景1结果...</div>

        <hr style="margin: 20px 0;">

        <h4>场景2: 模拟故障 &amp; 触发熔断 (ItemFeignClient)</h4>
        <p style="font-size: 0.9em; color: #555;">
            输入商品ID <code>-1</code> 来模拟 <code>cloud-second-hand</code> 应用内部调用失败。连续多次（例如5-10次，取决于熔断配置）输入 <code>-1</code> 并点击按钮，以触发熔断器从 CLOSED &rarr; OPEN。
            <br>观察：初期调用会显示降级，熔断器打开后，降级响应会非常迅速。
            <br><em>(此场景下，下游 <code>item-service</code> 是否实际运行不影响模拟结果，因为故障在 <code>cloud-second-hand</code> 内部模拟。)</em>
        </p>
        <div style="margin-top: 10px;">
            <input type="text" id="cbTestItemId2" value="-1" placeholder="输入 -1 模拟故障">
            <button id="cbTestButtonTriggerFailure" class="feign-test-button" style="background-color: #d9534f;">2. 多次调用 (ID: -1 模拟故障)</button>
        </div>
        <div id="cbTestResult2" class="test-result-area">场景2结果...</div>

        <hr style="margin: 20px 0;">

        <h4>场景3: 测试熔断器半开与恢复 (ItemFeignClient)</h4>
        <p style="font-size: 0.9em; color: #555;">
            1. (在场景2之后，熔断器已打开) 等待熔断配置中的 <code>waitDurationInOpenState</code> (例如10秒)。熔断器将进入 HALF_OPEN 状态。<br>
            2. 再次使用商品ID <code>-1</code> (模拟持续故障) 或一个<strong>存在的商品ID</strong> (例如: 1，模拟服务已恢复) 进行测试。<br>
            3. 点击下方按钮数次 (次数取决于 <code>permittedNumberOfCallsInHalfOpenState</code>，例如1-3次)。<br>
            观察：如果试探请求 (ID: 1) 成功，熔断器将关闭 (CLOSED)。如果试探请求 (ID: -1) 失败，熔断器将重新打开 (OPEN)。
            <br><em>(测试ID:1时，确保下游 <code>item-service</code> 正常运行。)</em>
        </p>
        <div style="margin-top: 10px;">
            <input type="text" id="cbTestItemId3" placeholder="输入 -1 或 存在的商品ID">
            <button id="cbTestButtonHalfOpen" class="feign-test-button" style="background-color: #f0ad4e;">3. 测试半开/恢复</button>
        </div>
        <div id="cbTestResult3" class="test-result-area">场景3结果...</div>

        <hr style="margin-top: 30px; margin-bottom: 20px;">
        <a href="index.html" class="back-link">返回首页</a>
        <a href="login.html" class="back-link" style="margin-left:10px;">返回登录页</a>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Helper function to perform the test and display results
        function performTest(itemId, resultDivId, buttonId) {
            const resultDiv = document.getElementById(resultDivId);
            resultDiv.textContent = '正在查询...';

            if (!itemId) {
                resultDiv.textContent = '请输入商品 ID。';
                return;
            }

            fetch(`/api/feign-test/item/${itemId}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 404) {
                            return response.json().then(errData => {
                                throw { status: 404, message: errData.message || '商品未找到 (404)。' };
                            }).catch(() => {
                                 throw { status: 404, message: '商品未找到 (404)。' };
                            });
                        }
                        return response.text().then(text => {
                            throw new Error(`HTTP error! status: ${response.status}, message: ${text}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data || !data.itemId) {
                        resultDiv.textContent = '未找到商品或返回数据格式不正确。';
                        console.log('Received unexpected data:', data);
                        return;
                    }

                    let output = '';
                    // Check for the new 'isDegraded' flag
                    if (data.degraded === true) {
                        output += `<strong style="color: orange;">熔断触发：服务降级中...</strong><br>`;
                        output += `<span style="color: orange;">商品信息加载中，请稍后重试</span><br><br>`;
                        output += `ID: ${data.itemId}<br>`;
                        output += `标题: ${data.title}<br>`;
                        output += `描述: ${data.description}<br>`;
                        output += `库存状态: <span style="font-weight: bold;">库存信息暂时不可用</span><br>`;
                    } else {
                        // Normal response
                        output += `<strong>商品信息 (正常调用):</strong><br>`;
                        output += `ID: ${data.itemId}<br>`;
                        output += `标题: ${data.title}<br>`;
                        output += `价格: ${data.price !== null ? data.price : 'N/A'}<br>`;
                        output += `分类: ${data.category || 'N/A'}<br>`;
                        output += `描述: ${data.description || '无'}<br>`;
                        output += `卖家ID: ${data.sellerId || 'N/A'}<br>`;
                        if (data.base64Image) {
                            output += `<img src="${data.base64Image}" alt="${data.title}" style="max-width: 100px; max-height: 100px; margin-top: 10px;"><br>`;
                        }
                    }
                    resultDiv.innerHTML = output;
                })
                .catch(error => {
                    const errorMessage = error.message || '未知错误';
                    // 专门处理为了触发熔断而模拟的后端500错误
                    if (errorMessage.includes("Simulated failure for itemId=-1")) {
                        let output = `<strong style="color: #d9534f;">记录到一次调用失败 (熔断器开启中...)</strong><br>`;
                        output += `<span style="color: #555;">这是一个模拟的后端错误，用于累积失败次数。当失败次数达到阈值 (当前配置为10次中的5次)，熔断器将打开，届时您将看到真正的“服务降级”信息。</span><br><br>`;
                        output += `<b>原始错误:</b> ${errorMessage}`;
                        resultDiv.innerHTML = output;
                    } else if (error.status === 404) {
                        resultDiv.textContent = error.message;
                    } else {
                        resultDiv.textContent = '测试失败: ' + errorMessage;
                    }
                    console.error('Test error:', error);
                });
        }

        const feignTestButton = document.getElementById('feignTestButton');
        if (feignTestButton) {
            feignTestButton.addEventListener('click', function() {
                const itemId = document.getElementById('feignTestItemId').value;
                performTest(itemId, 'feignTestResult', 'feignTestButton');
            });
        }

        const cbTestButtonStable = document.getElementById('cbTestButtonStable');
        if (cbTestButtonStable) {
            cbTestButtonStable.addEventListener('click', function() {
                const itemId = document.getElementById('cbTestItemId1').value;
                performTest(itemId, 'cbTestResult1', 'cbTestButtonStable');
            });
        }

        const cbTestButtonTriggerFailure = document.getElementById('cbTestButtonTriggerFailure');
        if (cbTestButtonTriggerFailure) {
            cbTestButtonTriggerFailure.addEventListener('click', function() {
                const itemId = document.getElementById('cbTestItemId2').value;
                performTest(itemId, 'cbTestResult2', 'cbTestButtonTriggerFailure');
            });
        }

        const cbTestButtonHalfOpen = document.getElementById('cbTestButtonHalfOpen');
        if (cbTestButtonHalfOpen) {
            cbTestButtonHalfOpen.addEventListener('click', function() {
                const itemId = document.getElementById('cbTestItemId3').value;
                performTest(itemId, 'cbTestResult3', 'cbTestButtonHalfOpen');
            });
        }
    });
    </script>
</body>
</html>
